package com.magical.controller;

import com.magical.entity.Files;
import com.magical.entity.RestJson;
import com.magical.entity.User;
import com.magical.service.FilesService;
import com.magical.service.UserService;
import com.magical.util.MyUtil;
import com.magical.util.ZipUtils;
import org.apache.ibatis.io.ResolverUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.*;
import java.util.*;
import java.util.zip.ZipOutputStream;


@Controller
@RequestMapping("/files")
public class FilesController {

    private Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private FilesService filesService;
    @Autowired
    private UserService userService;

    public void typeofFile(Files uploadFile) {
        String fileName = uploadFile.getFileName();
        // 获取文件后缀名并转化为写，用于后续比较
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
        // 创建图片类型数组
        String img[] = {"bmp", "jpg", "jpeg", "png", "tiff", "gif", "pcx", "tga", "exif", "fpx", "svg", "psd",
                "cdr", "pcd", "dxf", "ufo", "eps", "ai", "raw", "wmf"};
        for (int i = 0; i < img.length; i++) {
            if (img[i].equals(fileType)) {
                uploadFile.setFiletypeId(7);
            }
        }
        // 创建文档类型数组
        String document[] = {"txt", "doc", "docx", "xls", "htm", "html", "jsp", "rtf", "wpd", "pdf", "ppt"};
        for (int i = 0; i < document.length; i++) {
            if (document[i].equals(fileType)) {
                uploadFile.setFiletypeId(6);
            }
        }
        // 创建视频类型数组
        String video[] = {"mp4", "avi", "mov", "wmv", "asf", "navi", "3gp", "mkv", "f4v", "rmvb", "webm"};
        for (int i = 0; i < video.length; i++) {
            if (video[i].equals(fileType)) {
                uploadFile.setFiletypeId(9);
            }
        }
        // 创建音乐类型数组
        String music[] = {"mp3", "wma", "wav", "mod", "ra", "cd", "md", "asf", "aac", "vqf", "ape", "mid", "ogg",
                "m4a", "vqf"};
        for (int i = 0; i < music.length; i++) {
            if (music[i].equals(fileType)) {
                uploadFile.setFiletypeId(8);
            }
        }
        uploadFile.setFiletypeId(15);
    }

    /*
    根据文件名称判断文件类型
     */

    public int sizeofDirectory(String fileDir, int size) {
        File file = new File(fileDir);
        File[] files = file.listFiles();
        if (files == null)
            return 0;
        for (File f : files) {
            if (f.isFile()) {
                size += (int) f.length();
            } else if (f.isDirectory()) {
                sizeofDirectory(f.getAbsolutePath(), size);
            }
        }
        return size;
    }

    public List<File> loadFiles(int userId, String fileDir, String ParentId) throws IOException {

        System.out.println("LoadFiles");
        List<File> list = new ArrayList<File>();
        File file = new File(fileDir);
        File[] files = file.listFiles();
        if (files == null)
            return null;
        for (File f : files) {
            if (f.isFile()) {
                Files temp = new Files();
                String fileId = MyUtil.generateFileId(f.getName());
                String originalFilename = f.getName();
                String filepath = f.getAbsolutePath();
                int size = (int) f.length();
                String type = null;
                try {
                    type = java.nio.file.Files.probeContentType(f.toPath()).split("/")[0];
                } catch (Exception e) {
                    type = "other";
                }
                System.out.println(type);
                temp.setFileId(fileId);
                temp.setFileName(originalFilename);
                temp.setFileSize(size);
                temp.setUserId(userId);
                temp.setFatherId(ParentId);
                temp.setFullPath(filepath);
                typeofFile(temp);
                filesService.upload(temp);
                list.add(f);
            } else if (f.isDirectory()) {
                Files temp = new Files();
                String fileId = MyUtil.generateFileId(f.getName());
                String originalFilename = f.getName();
                String filepath = f.getAbsolutePath();
                int size = sizeofDirectory(filepath, 0);
                String type = "Directory";
                System.out.println(type);
                temp.setFileId(fileId);
                temp.setFileName(originalFilename);
                temp.setFileSize(size);
                temp.setUserId(userId);
                temp.setFatherId(ParentId);
                temp.setFullPath(filepath);
                temp.setFiletypeId(5);
                filesService.upload(temp);
                loadFiles(userId, f.getAbsolutePath(), fileId);
            }
        }
        for (File f1 : list) {
            System.out.println(f1.getName());
        }
        return list;
    }

    @RequestMapping("/AnUploadFiles")
    @ResponseBody
    public RestJson<Files> AnUploadFile(HttpServletRequest request) throws IOException {
        logger.info("AnUploadFiles");
        RestJson<Files> result = new RestJson<>();
        int userId = Integer.parseInt(request.getParameter("userId"));
        String parentId = request.getParameter("folderId");
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next());
                String path = filesService.findById(parentId).getFullPath() + "/";//父文件夹路径
                String originalFilename = file.getOriginalFilename();//原本的文件名
                String filePath = path + originalFilename;//文件路径
                logger.warn("filePath: " + filePath);
                File parent = new File(path);//父文件夹、用于重名检测
                String[] s = parent.list();
                String newname = MyUtil.autoRenameFile(parent.list(), originalFilename);//重命名之后的文件名
                File dest = new File(parent.getAbsolutePath() + "/" + newname);//上传路径
                try {
                    file.transferTo(dest);
                    Files uploadFile = new Files();
                    String fileId = MyUtil.generateFileId(originalFilename);//生成文件ID
                    int size = (int) file.getSize();//文件大小
                    uploadFile.setFileId(fileId);
                    uploadFile.setFileName(newname);
                    uploadFile.setFileSize(size);
                    uploadFile.setUserId(userId);
                    uploadFile.setFatherId(parentId);
                    uploadFile.setFullPath(dest.getAbsolutePath());
                    typeofFile(uploadFile);
                    try {
                        filesService.upload(uploadFile);
                        userService.usedSpace(userId, size);
                        result.setCode(0);
                    } catch (Exception ioe) {
                        result.setCode(-1);
                        result.setMessage("上传文件失败");
                        logger.warn(ioe.getMessage());
                    }
                } catch (Exception e) {
                    logger.warn(e.getMessage());
                }
            }
        }
        return result;
    }

    @RequestMapping("/uploadFiles")
    @ResponseBody
    public String uploadFiles(HttpServletRequest request) throws IOException {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("files");
        String parentId = request.getParameter("parent");
        String[] paths = request.getParameterValues("paths");
        if (!files.isEmpty()) {
            String path = filesService.findById(parentId).getFullPath() + "/";
            File root = new File(path);
            File file = new File(path + paths[0]).getParentFile();
            String rootName = paths[0].split("/")[0];
            File[] rootDir = root.listFiles();
            for (File f : rootDir)
                if (f.getName().equals(rootName))
                    file = f;
            if (file.exists()) {
                File parent = file.getParentFile();
                String newname = MyUtil.autoRenameFile(parent.list(), file.getName());
                File newfile = new File(parent.getAbsolutePath() + "/" + newname);
                file.renameTo(newfile);
                file = newfile;
                //file.mkdirs();
            }
            for (int i = 0; i < paths.length; i++) {
                File temp = new File(path + paths[i]);
                if (!temp.getParentFile().exists())
                    temp.getParentFile().mkdirs();
                if (!temp.exists())
                    files.get(i).transferTo(temp);
            }
            try {
                Files temp = new Files();
                String originalFilename = file.getName();
                String fileId = MyUtil.generateFileId(originalFilename);
                String filepath = file.getAbsolutePath();
                int size = sizeofDirectory(filepath, 0);
                String type = "Directory";
                System.out.println(type);
                temp.setFileId(fileId);
                temp.setFileName(originalFilename);
                temp.setFileSize(0);
                temp.setUserId(userId);
                temp.setFatherId(parentId);
                temp.setFullPath(filepath);
                temp.setFiletypeId(5);
                filesService.upload(temp);
                userService.usedSpace(userId, size);
                loadFiles(userId, file.getAbsolutePath(), temp.getFileId());
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("失败了");
            }
        }
        return "success";
    }

    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(HttpServletRequest request) throws IOException {

        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        String parentId = request.getParameter("parent");
        if (!file.isEmpty()) {
            String path = filesService.findById(parentId).getFullPath() + "/";
            String originalFilename = file.getOriginalFilename();
            String fileId = MyUtil.generateFileId(originalFilename);
            String filePath = path + originalFilename;
            System.out.println("filePath: " + filePath);
            int size = (int) file.getSize();
            File parent = new File(path);
            String newname = MyUtil.autoRenameFile(parent.list(), originalFilename);
            File newfile = new File(parent.getAbsolutePath() + "/" + newname);
            File dest = new File(filePath);
            dest.renameTo(newfile);
            if (!(dest.exists())) {
                file.transferTo(dest);
                Files uploadFile = new Files();
                uploadFile.setFileId(fileId);
                uploadFile.setFileName(newname);
                uploadFile.setFileSize(size);
                uploadFile.setUserId(userId);
                uploadFile.setFatherId(parentId);
                uploadFile.setFullPath(newfile.getAbsolutePath());
                typeofFile(uploadFile);
                try {
                    filesService.upload(uploadFile);
                    userService.usedSpace(userId, size);
                    return uploadFile.getFileId();
                } catch (Exception e) {
                    e.printStackTrace();
                    return "failed";
                }
            }
        }
        return "success";
    }

    @RequestMapping("/findSubfile")
    @ResponseBody
    public List<Files> findSubfile(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        String id = request.getParameter("folderId");
        return filesService.findSubfile(id);
    }

    @RequestMapping("/ADfindSubfile")
    @ResponseBody
    public RestJson<List<Files>> ADfindSubfile(HttpServletRequest request) {
        String id = request.getParameter("folderId");
        RestJson<List<Files>> result = new RestJson<>();
        List<Files> files = filesService.findSubfile(id);
        if (files != null) {
            result.setData(files);
        } else {
            result.setCode(-1);
            result.setMessage("异常错误");
        }
        return result;
    }

    /**
     * 主界面文件夹的查询 ph
     *
     * @param request
     * @return
     */
    @RequestMapping("/search")
    public ModelAndView searchFile(HttpServletRequest request) {
        ModelAndView modelAndView = search(request);
        modelAndView.setViewName("/index.jsp");
        return modelAndView;
    }

    /**
     * 选择文件夹的查询 ph
     *
     * @param request
     * @return
     */
    @RequestMapping("/search2")
    public ModelAndView searchFile2(HttpServletRequest request) {
        ModelAndView modelAndView = search(request);
        String ids = request.getParameter("idss");
        modelAndView.setViewName("/relocation.jsp");
        modelAndView.addObject("idss", ids);
        return modelAndView;
    }

    private ModelAndView search(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        String id = request.getParameter("folderId");
        String ids = request.getParameter("path");          //获取前台传过来的id 路径
        ModelAndView modelAndView = new ModelAndView();
        if (ids == null) ids = id;
        String[] idss = ids.split("-");                 //分割id路径
        List<Files> result = filesService.findSubfile(id);    //此文件夹需要展示的子目录
        Files files = filesService.findById(id);              //当前所在文件夹的信息
        if (files != null) {
            String newids = "";                                  //形成新路径
            for (int i = 0; i < idss.length; i++) {
                if (files.getFileId().equals(idss[i])) {
                    for (int j = 0; j <= i; j++)
                        newids += idss[j] + "-";
                    break;
                }
                if (i == idss.length - 1) {
                    newids = ids + files.getFileId() + "-";              //为路径添加新的id
                }
            }
            modelAndView.addObject("file", files);
            modelAndView.addObject("ids", newids);
        }
        modelAndView.addObject("subfiles", result);

        return modelAndView;
    }

    @RequestMapping("/vagueSearchFile")
    @ResponseBody
    public List<Files> vagueSearchFile(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        String value = request.getParameter("value");
        return filesService.vagueSearchFile(value, userId);

    }

    @RequestMapping("/ADvagueSearchFile")
    @ResponseBody
    public RestJson<List<Files>> ADvagueSearchFile(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userId = Integer.parseInt(request.getParameter("userId"));
        String value = request.getParameter("value");

        List<Files> files = filesService.vagueSearchFile(value, userId);
        RestJson<List<Files>> result = new RestJson<>();
        if (files == null) {
            result.setCode(-1);
            result.setMessage("emptyfile");
            return result;


        } else {
            result.setData(files);
            return result;
        }

    }

    @RequestMapping("/renameFile")
    @ResponseBody
    public String renameFile(HttpServletRequest request) {
        String id = request.getParameter("id");
        String newname = request.getParameter("name");
        Files file = filesService.findById(id);
        if (newname.equals(file.getFileName()))
            return "success";
        File originalFile = new File(file.getFullPath());
        File parent = originalFile.getParentFile();
        newname = MyUtil.autoRenameFile(parent.list(), newname);
        File newfile = new File(parent.getAbsolutePath() + "/" + newname);
        originalFile.renameTo(newfile);
        filesService.renameFile(id, newname);
        return "success";
    }

    @RequestMapping("/moveFiles")
    @ResponseBody
    public String moveFiles(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        String[] fromDirID = request.getParameter("files").split(",");
        String toDirID = request.getParameter("moveto");
        Files to = filesService.findById(toDirID);
        for (String f : fromDirID) {
            Files from = filesService.findById(f);
            String newPath = to.getFullPath();
            try {
                moveFile(from.getFullPath(), newPath + "/" + from.getFileName());
            } catch (Exception e) {
                File newFile = new File(to.getFullPath());
                String newname = MyUtil.autoRenameFile(newFile.list(), from.getFileName());
                moveFile(from.getFullPath(), newPath + "/" + newname);
                from.setFileName(newname);
            }
            try {
                filesService.moveFiles(from, to, userId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "success";
    }

    public void moveFile(String from, String to) throws Exception {
        Path pathFrom = Paths.get(from);
        Path pathTo = Paths.get(to);
        java.nio.file.Files.move(pathFrom, pathTo, StandardCopyOption.ATOMIC_MOVE);
    }

    @RequestMapping("/AnCopyFiles")
    @ResponseBody
    public RestJson<Files> AnCopyFiles(HttpServletRequest request) {
        RestJson<Files> result = new RestJson<>();
        int userId = Integer.parseInt(request.getParameter("userId"));
        String[] fromDirID = request.getParameter("files").split(",");
        String toDirID = request.getParameter("copyto");
        Files to = filesService.findById(toDirID);
        for (String f : fromDirID) {
            Files from = filesService.findById(f);
            String newPath = to.getFullPath();
            try {
                File parent = new File(newPath);
                String newname = MyUtil.autoRenameFile(parent.list(), from.getFileName());
                copyFile(from.getFullPath(), to.getFullPath());
                if (from.getFiletypeId() == 5) {
                    Files copiedDir = new Files();
                    String copiedId = MyUtil.generateFileId(from.getFileName());
                    copiedDir.setFileId(copiedId);
                    copiedDir.setFatherId(to.getFileId());
                    copiedDir.setFileName(from.getFileName());
                    copiedDir.setUserId(userId);
                    copiedDir.setFileSize(0);
                    copiedDir.setFiletypeId(5);
                    copiedDir.setFullPath(newPath + "/" + from.getFileName());
                    filesService.upload(copiedDir);
                    loadFiles(userId, newPath + "/" + from.getFileName(), copiedId);
                    userService.usedSpace(userId, sizeofDirectory(newPath + "/" + from.getFileName(), 0));
                } else {
                    String fileId = MyUtil.generateFileId(newname);
                    from.setFileId(fileId);
                    from.setUserId(userId);
                    from.setFullPath(newPath + "/" + newname);
                    from.setFileName(newname);
                    from.setFatherId(to.getFileId());
                    filesService.upload(from);
                    userService.usedSpace(userId, from.getFileSize());
                    result.setCode(0);
                }
            } catch (Exception e) {
                logger.warn("Copy files failed.");
                result.setCode(-1);
            }
        }
        return result;
    }

    @RequestMapping("/copyFiles")
    @ResponseBody
    public String copyFiles(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        String[] fromDirID = request.getParameter("files").split(",");
        String toDirID = request.getParameter("copyto");
        Files to = filesService.findById(toDirID);
        for (String f : fromDirID) {
            Files from = filesService.findById(f);
            String newPath = to.getFullPath();
            try {
                File parent = new File(newPath);
                String newname = MyUtil.autoRenameFile(parent.list(), from.getFileName());
                copyFile(from.getFullPath(), to.getFullPath());
                if (from.getFiletypeId() == 5) {
                    Files copiedDir = new Files();
                    String copiedId = MyUtil.generateFileId(from.getFileName());
                    copiedDir.setFileId(copiedId);
                    copiedDir.setFatherId(to.getFileId());
                    copiedDir.setFileName(from.getFileName());
                    copiedDir.setUserId(userId);
                    copiedDir.setFileSize(0);
                    copiedDir.setFiletypeId(5);
                    copiedDir.setFullPath(newPath + "/" + from.getFileName());
                    filesService.upload(copiedDir);
                    loadFiles(userId, newPath + "/" + from.getFileName(), copiedId);
                    userService.usedSpace(userId, sizeofDirectory(newPath + "/" + from.getFileName(), 0));
                } else {
                    String fileId = MyUtil.generateFileId(newname);
                    from.setFileId(fileId);
                    from.setUserId(userId);
                    from.setFullPath(newPath + "/" + newname);
                    from.setFileName(newname);
                    from.setFatherId(to.getFileId());
                    filesService.upload(from);
                    userService.usedSpace(userId, from.getFileSize());
                }
            } catch (Exception e) {
                e.printStackTrace();
                return "error";
            }
        }
        return "success";
    }

    public void copyFile(String from, String to) throws IOException {
        File fromDir = new File(from);
        File toDir = new File(to);
        String newname = null;
        if (fromDir.isDirectory()) {
            try {
                copy(from, to + "/" + fromDir.getName());
            } catch (FileAlreadyExistsException e) {
                newname = MyUtil.autoRenameFile(toDir.list(), fromDir.getName());
                copy(fromDir.getAbsolutePath(), to + "/" + newname);
            }
        } else {
            try {
                copy(from, to + "/" + fromDir.getName());
            } catch (FileAlreadyExistsException e) {
                String filenewname = MyUtil.autoRenameFile(toDir.list(), fromDir.getName());
                copy(fromDir.getAbsolutePath(), to + "/" + filenewname);
            }
            return;
        }
        File[] files = fromDir.listFiles();
        for (File f : files) {
            System.out.println(f.getAbsolutePath());
            copyFile(f.getAbsolutePath(), to + "/" + (newname == null ? fromDir.getName() : newname));
        }
    }

    public void copy(String from, String to) throws IOException {
        Path pathFrom = Paths.get(from);
        Path pathTo = Paths.get(to);
        java.nio.file.Files.copy(pathFrom, pathTo, StandardCopyOption.COPY_ATTRIBUTES);
    }

    @RequestMapping("/deleteFiles")
    @ResponseBody
    public String deleteFile(String[] ids, HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        for (int i = 0; i < ids.length - 1; i++) {
            Files temp = filesService.findRecycleById(ids[i]);
            String path = temp.getFullPath();
            File file = new File(path);
            if (!file.isDirectory())
                try {
                    file.delete();
                    filesService.delete(temp.getFileId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            else {
                try {
                    deleteDirectory(path);
                    filesService.deleteDirectory(temp.getFileId());
                    return "success";
                } catch (Exception e) {
                    return "error";
                }
            }
        }
        return "success";
    }

    public void deleteDirectory(String path) {
        File file = new File(path);
        if (!file.exists())
            return;
        if (!file.isDirectory())
            return;
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isFile())
                f.delete();
            else
                deleteDirectory(f.getAbsolutePath());
        }
        file.delete();
    }

    @RequestMapping("/FalseDel")
    @ResponseBody
    public String FalseDel(String[] ids, HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        for (int i = 0; i < ids.length - 1; i++) {
            Files f = filesService.findById(ids[i]);
            if (f.getFiletypeId() == 5) {
                int size = sizeofDirectory(f.getFullPath(), 0);
                userService.usedSpace(userId, -size);
                filesService.falesdeleteById(1, ids[i]);
            } else {
                userService.usedSpace(userId, -f.getFileSize());
                filesService.falseDelDirectory(ids[i]);
            }
        }
        return "success";
    }

    //删除Tab
    @RequestMapping("/deleteTab")
    @ResponseBody
    public String deleteTab(String id, HttpServletRequest request) {
        String[] ids = {id};
        try {
            FalseDel(ids, request);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }

    //按文件类型显示文件
    @RequestMapping("/findFilesByType")
    @ResponseBody
    public List<Files> findFilesByType(int fileType, HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        List<Files> files = filesService.showFilesByType(userId, fileType);
/*        if(fileType==5&&files!=null) {
            for (Files f : files) {
                if (f.getFileId().equals(String.valueOf(userId)))
                    files.remove(f);
            }
        }*/
        return files;
    }


    //显示回收站
    @RequestMapping("/showRecycle")
    @ResponseBody
    public List<Files> showRecycle(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        return filesService.selectDelected(userId);
    }

    @RequestMapping("/ADshowRecycle")
    @ResponseBody
    public RestJson<List<Files>> ADshowRecycle(HttpServletRequest request) {
        String userId = request.getParameter("u");
        List<Files> files = filesService.selectDelected(Integer.parseInt(userId));
        RestJson<List<Files>> result = new RestJson<>();
        if (files == null) {
            result.setCode(-1);
            result.setMessage("回收站为空!");
            return result;
        } else {
            result.setData(files);
            return result;
        }
    }

    //恢复文件
    @RequestMapping("/recovereFiles")
    @ResponseBody
    public String recovereFiles(String[] ids, HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        for (int i = 0; i < ids.length - 1; i++) {
            Files f = filesService.findRecycleById(ids[i]);
            int size = f.getFileSize();
            if (f.getFiletypeId() == 5)
                size = sizeofDirectory(f.getFullPath(), 0);
            userService.usedSpace(userId, size);
            filesService.falesdeleteById(0, ids[i]);
        }
        return "success";
    }

    //手机新建文件夹
    @RequestMapping("/AnAddDirectory")
    @ResponseBody
    public RestJson<Files> AnaddDirectory(HttpServletRequest request) {
        RestJson<Files> result = new RestJson<>();
        int userId = Integer.parseInt(request.getParameter("userId"));
        String parentId = request.getParameter("folderId");
        String name = request.getParameter("directoryName");
        Files file = filesService.findById(parentId);
        String path = file.getFullPath();
        File parent = new File(path);
        String newname = name;
        newname = MyUtil.autoRenameFile(parent.list(), name);
        File newDir = new File(path + "/" + newname);
        newDir.mkdirs();
        Files temp = new Files();
        String originalFilename = newname;
        String fileId = MyUtil.generateFileId(originalFilename);
        String filepath = path + "/" + newname;
        temp.setFileId(fileId);
        temp.setFileName(originalFilename);
        temp.setFileSize(0);
        temp.setUserId(userId);
        temp.setFatherId(parentId);
        temp.setFullPath(filepath);
        temp.setFiletypeId(5);
        try {
            filesService.upload(temp);
            result.setCode(0);
        } catch (Exception e) {
            result.setCode(-1);
            logger.warn("Add directory failed.");
        }
        return result;
    }

    //新建文件夹
    @RequestMapping("/addDirectory")
    @ResponseBody
    public String addDirectory(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int userId = ((User) session.getAttribute("loginUser")).getId();
        String id = request.getParameter("directoryId");
        String name = request.getParameter("directoryName");
        Files file = filesService.findById(id);
        String path = file.getFullPath();
        File parent = new File(path);
        String newname = name;
        if (parent.list() != null)
            newname = MyUtil.autoRenameFile(parent.list(), name);
        File newDir = new File(path + "/" + newname);
        try {
            newDir.mkdirs();
        } catch (Exception e) {
            return "error";
        }
        Files temp = new Files();
        String originalFilename = newname;
        String fileId = MyUtil.generateFileId(originalFilename);
        String filepath = path + "/" + newname;
        temp.setFileId(fileId);
        temp.setFileName(originalFilename);
        temp.setFileSize(0);
        temp.setUserId(userId);
        temp.setFatherId(id);
        temp.setFullPath(filepath);
        temp.setFiletypeId(5);
        filesService.upload(temp);
        return "success";
    }

    //下载文件
    @RequestMapping("/downloadFile")
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String id = request.getParameter("ids");//888,999,00;
        String[] idArr = id.split(",");

        if (idArr.length == 1) {
            Files file = filesService.findById(idArr[0]);
            String fileName = file.getFullPath();
            //获取输入流
            InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
            //假如以中文名下载的话
            String filename = file.getFileName();

            //转码，免得文件名中文乱码
            filename = URLEncoder.encode(filename, "UTF-8");
            //设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            while ((len = bis.read()) != -1) {
                out.write(len);
                out.flush();
            }
            out.close();

        } else {
            String zipName = "myfile.zip";
            response.setContentType("APPLICATION/OCTET-STREAM");
            response.setHeader("Content-Disposition", "attachment; filename=" + zipName);
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
            try {
                for (int i = 0; i < idArr.length; i++) {
                    Files f = filesService.findById(idArr[i]);
                    ZipUtils.doCompress(f.getFullPath(), out);
                    response.flushBuffer();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                out.close();

            }
        }
    }
}
